<template>
  <component
    :is="data.formComp"
    ref="docPage"
    :createTime="createTime"
    :data="data"
    :otherData="otherData"
    :records="records"
    :type="type"
    :form-type="formType"
    @setCanOperate="setCanOperate"
    @update="handleClose"
    @save="save"
  />
</template>

<script>
import { endOfDay, startOfDay } from 'date-fns'
import { computed, defineComponent, reactive, toRefs, watch } from 'vue'

import { Doc } from '@/api/doc/index'
import DateSelection from '@/components/DateSelection/indexV2.vue'
import {
  getBusFromInstance,
  getElementFnFromInstance,
  getStoreFromInstance
} from '@/utils/instance'

import CBP from './CBP/index.vue'
import DifficultConsultation from './DifficultConsultation/index.vue'
import EndoscopeOperate from './EndoscopeOperate/index.vue'
import FallMonitoring from './FallMonitoring/index.vue'
import HandoverRecord from './HandoverRecord/index.vue'
import HealthEducation from './HealthEducation/index.vue'
import InterveneHandover from './InterveneHandover/index.vue'
import MissuctionRisk from './MissuctionRisk/index.vue'
import PICC from './PICC/index.vue'
import PICCRisk from './PICCRisk/index.vue'
import PressureApplication from './PressureApplication/index.vue'
import PressureMonitoring from './PressureMonitoring/index.vue'
import RyAdultEstimate from './RyAdultEstimate/index.vue'
import SurgicalHandover from './SurgicalHandover/index.vue'
import TCMNursingDialectical from './TCMNursingDialectical/index.vue'
import Vte from './Vte/index.vue'

const typeMap = {
  add: '新增',
  edit: '修改',
  // 文书组件在type值为`打印`时加上一层遮罩
  view: '打印'
}

export default defineComponent({
  name: 'DocForm',
  components: {
    DateSelection,
    CBP,
    TCMNursingDialectical,
    Vte,
    FallMonitoring,
    PressureMonitoring,
    HealthEducation,
    MissuctionRisk,
    RyAdultEstimate,
    PressureApplication,
    HandoverRecord,
    EndoscopeOperate,
    SurgicalHandover,
    InterveneHandover,
    PICC,
    PICCRisk,
    DifficultConsultation
  },
  props: {
    data: {
      type: Object,
      default: () => ({})
    },
    otherData: {
      type: Object,
      default: () => {}
    }
  },
  emits: ['refresh'],
  setup(props, { emit }) {
    const state = reactive({
      loading: false,
      type: '',
      records: [],
      createTime: null,
      formType: 'add',
      pickerOptions: {},
      operateType: '', // 操作类型
      canOperate: false, // 用来判断是否能执行自动打印
      printTimer: null, // 定时器对象
      docPage: {},
      recordTime: null
    })

    const store = getStoreFromInstance()
    const { $message } = getElementFnFromInstance()
    const bus = getBusFromInstance()
    const patCur = computed(() => store.getters.patCur)

    const user = computed(() => store.getters.user)

    const roles = computed(() => store.getters.roles)

    const isHistory = computed(() => store.getters.isHistory)
    const isFlow = computed(() => store.getters.isFlow)

    function setCanOperate(f) {
      state.canOperate = f
    }

    function setOperateType(t) {
      state.operateType = t
    }

    function handleCreateTimeChange(e) {
      if (!patCur.value) {
        return
      }
      if (patCur.value.startRkTime && e < patCur.value.startRkTime) {
        state.createTime = patCur.value.startRkTime
      } else if (patCur.value.endCkTime && e > patCur.value.endCkTime) {
        state.createTime = patCur.value.endCkTime
      }
    }

    /**
     * 新增/修改
     */
    async function initEditData(id, type = 'add') {
      state.formType = type
      const patCur = store.getters.patCur

      if (id) {
        //修改
        const { data } = await Doc.getInfo(id)
        state.type = typeMap[type]
        if (type == 'add') {
          delete data.id
          delete data.createdBy
          delete data.createTime
          delete data.updatedBy
          delete data.updateTime

          state.createTime = patCur.endCkTime
            ? patCur.endCkTime
            : new Date().getTime()
        } else if (type == 'edit') {
          // 编辑需要使用记录时间
          state.createTime = new Date(data.createTime).getTime()
        }
        state.records = [data]
      } else {
        //新增
        state.type = '新增'
        state.records = [{ jsonText: null }]
        state.createTime = patCur.endCkTime
          ? patCur.endCkTime
          : new Date().getTime()
      }
      state.visible = true
    }

    async function save() {
      // if (props.data.type == '33') {
      //   state.docPage.save()
      //   return
      // }
      const form = state.docPage.getParams() || {}
      form.recordTime = state.recordTime
      // 压疮 评分必填
      if (props.data.type == 53) {
        const _form = JSON.parse(form.jsonText)
        const arr = [
          'braden1',
          'braden2',
          'braden3',
          'braden4',
          'braden5',
          'braden6'
        ]
        let pass = true
        arr.map(res => {
          if (!_form[res]) {
            pass = false
            return
          }
        })
        if (!pass) {
          $message.error('请勾选完整Braden评分！')
          return
        }
      }
      if (form.createTime) {
        // form.createTime = new Date(form.createTime).getTime();
        form.createTime = state.createTime
      }
      // 修改
      if (form.id) {
        await Doc.edit(form)
      } else {
        // 新增
        const params = {
          id: '',
          patientIdent: patCur.value.patientIdent,
          gender: patCur.value.gender,
          jsonText: form.jsonText,
          type: props.data.type,
          bedNumber: patCur.value.bedNumber,
          patientName: patCur.value.patientName,
          wardName: patCur.value.wardName,
          hospitalNumber: patCur.value.hospitalNumber,
          docName: props.data.title,
          createTime: state.createTime,
          recordTime: state.createTime
        }
        await Doc.add(params)
      }
      $message.success(`保存成功`)
      handleClose()
    }

    function reset() {
      state.docPage.reset()
    }
    function add() {
      state.docPage.add()
    }

    function handleClose() {
      state.records = []
      setOperateType('')
      emit('refresh')
    }

    watch(
      () => props.data.formComp,
      (n, o) => {
        if (n != o) {
          setCanOperate(false)
        }
      }
    )

    watch(
      () => state.canOperate,
      n => {
        // printDoc()
      }
    )

    bus.$on('recordTime', data => {
      state.recordTime = data
    })

    return {
      ...toRefs(state),
      isHistory,
      isFlow,
      user,
      roles,
      initEditData,
      handleCreateTimeChange,
      save,
      add,
      reset,
      setCanOperate,
      handleClose
    }
  }
})
</script>

<style lang="scss" scoped>
.docForm {
  position: relative;
}

.timePickerWrap {
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  margin: 0 auto;
  padding: 10px 20px;
  z-index: 1000;
  background-color: #fff;

  .left {
    display: flex;
    align-items: center;
  }
}
</style>
./FallMonitoring/index.vue
